import 'package:flutter/cupertino.dart';

class WrapContentHeightSliverHeader extends StatefulWidget {
  Widget child;
  bool? pinned;

  WrapContentHeightSliverHeader({required this.child, this.pinned = false});

  @override
  State<StatefulWidget> createState() => _WrapContentHeightSliverHeaderState();
}

class _WrapContentHeightSliverHeaderState
    extends State<WrapContentHeightSliverHeader> {
  final GlobalKey _key = GlobalKey();
  double height = double.infinity;

  late BoxConstraints constraints;

  @override
  void didChangeDependencies() {
    WidgetsBinding.instance.addPostFrameCallback(_getContainerHeight);
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(WrapContentHeightSliverHeader oldWidget) {
    WidgetsBinding.instance.addPostFrameCallback(_getContainerHeight);
    super.didUpdateWidget(oldWidget);
  }

  _getContainerHeight(_){
    height = _key.currentContext?.size?.height ?? 200;
    setState(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    return SliverPersistentHeader(
      pinned: widget.pinned!,
      delegate: StickyWidgetDelegate(
        height: height,
        child: OverflowBox(
          maxHeight: MediaQuery.of(context).size.height,
            child: ConstrainedBox(
              key: _key,
                constraints: constraints = BoxConstraints.loose(
                    Size(double.infinity, double.infinity)),
                child: widget.child)),
      ),
    );
  }
}

class StickyWidgetDelegate extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double height;

  StickyWidgetDelegate({required this.child, required this.height});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      child: this.child,
    );
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
